const zbToolBar = function() {
    this.barId = '';
    this.activeClass = 'zb-toolbar-active';
    this.position = 'bottom'; //bottom/top
    this.content = ''; //string
    this.contentNode = null;
    this.onClick = function () {
        console.log(this);
    }

    this.tpl_text =
        '<div class="zb-toolbar {position}" id="{id}">\
            <div class="zb-toolbar-text {style}" id="{id}">{name}</div>\
        </div>';

    this.initCss = function() {
        let flag = document.getElementsByClassName('zb-toolbar');
        if (!flag || flag.length === 0) {
            let style = document.createElement('style');
            style.innerText =
                '.zb-toolbar {z-index:999; display: flex;flex-direction: row;justify-content: space-around; align-items: stretch; height:6.5%; background-color:#f9f9f9;}'+
                '.zb-toolbar-position-top{position: fixed;left: 0; top: 0; right: 0; box-shadow:0 0 4px rgba(0, 0, 0, 0.2);}'+
                '.zb-toolbar-position-bottom{position: fixed;left: 0; bottom: 0; right: 0; box-shadow:0 0 4px rgba(0, 0, 0, 0.2);}'+
                '.zb-toolbar-text{font-size: 0.8rem; flex-grow:1;display: flex;flex-direction:column; justify-content:center; text-align:center;}'
            ;

            let head = document.getElementsByTagName('head')[0];
            head.appendChild(style);
        }
    }

    //初始化
    //config: {id: 控件id, position: bottom/top (底部/顶部工具栏)， type: text(纯文字)}
    this.init = function(data, config){
        this.initCss();

        //id
        this.barId = config['id'] ? config['id'] : '';

        //高亮的样式
        if (config && config['active_class']) {
            this.activeClass = config['active_class'];
        }

        //选择模板
        this.type = config['type'] ? config['type'] : 'text';
        let node = null;
        switch(this.type){
            case 'text':
                node = this.htmlToNode(this.tpl_text);
                break;
            default:
                node = this.htmlToNode(this.tpl_text);
                break;

        }

        //工具栏位置
        this.position = config['position'] ? config['position'] : 'bottom';
        let position = this.position === 'bottom' ? 'zb-toolbar-position-bottom' : 'zb-toolbar-position-top';

        //组装数据
        for (let i=0; i<data.length; i++) {
            data[i]['id'] = data[i]['id'] ? data[i]['id'] : '';
        }

        let struct = [
            {
                'id': this.barId,
                'position': position,
                'zb-toolbar-text' : data
            }
        ];

        this.content = this.repeatNode(node, struct);
        this.contentNode = this.htmlToNode(this.content);
        //绑定事件
        let items = this.contentNode.getElementsByClassName('zb-toolbar-text');
        for (let i=0; i<items.length; i++) {
            items[i].addEventListener('click', this.onClick.bind(items[i]));
        }
    }

    //隐藏工具栏中的按钮
    this.hideItem = function(id) {
        document.getElementById(id).style.display = 'none';
    }

    this.addItem = function(item){
        // 尽量不要有此动作, 而是整体渲染, 防止混乱
    }

    this.hide = function () {
        document.getElementById(this.barId).style.display = 'none';
    }

    this.show = function () {
        document.getElementById(this.barId).style.display = '';
    }

    this.htmlToNode = function(html) {
        let div = document.createElement('div');
        div.innerHTML = html;
        return div.firstElementChild;
    }

    //覆盖指定id的dom元素
    this.replaceNode = function (id){
        let old = document.getElementById(id);
        let parent = old.parentNode;
        parent.replaceChild(this.contentNode, old);
    }

    /**
     * 根据json渲染DOM节点
     * @param node HTML DOM节点, 注意不是string
     * @param arr json数组 注意是数组类型
     * @return string 返回HTML字符串, 注意不是DOM节点
     */
    this.repeatNode = function (node, arr) {
        let out = [];
        for (let i=0; i<arr.length; i++) {
            let tmp = node.outerHTML;
            tmp = tmp.replace(/\s/g, ' '); //去掉回车换行, 减少空白符

            let map = arr[i];

            //先渲染内层的数组
            for (let j in map) {
                if (map[j] instanceof Array) { //数组, 递归替换
                    let subNode = node.querySelector('.'+j);
                    if (subNode) {
                        let subHtml = this.repeatNode(subNode, map[j]); //递归
                        let subTpl = subNode.outerHTML.replace(/\s/g, ' ');
                        tmp = tmp.replace(subTpl, subHtml);
                    }
                }
            }

            //再渲染内层的对象
            for (let j in map) {
                if (map[j] instanceof Object && !(map[j] instanceof Array)) { //对象, 递归替换
                    let subNode = node.querySelector('.'+j);
                    if (subNode) {
                        let subHtml = this.repeatNode(subNode, [map[j]]); //递归
                        let subTpl = subNode.outerHTML.replace(/\s/g, ' ')
                        tmp = tmp.replace(subTpl, subHtml);
                    }
                }
            }

            //最后渲染外层的键值对/字符串
            for (let j in map) {
                if (typeof map[j] === 'string' || typeof map[j] === 'number') { //字符串, 直接替换
                    let re = new RegExp('{' + j + '}', 'g');
                    tmp = tmp.replace(re, map[j]);
                }
            }

            out.push(tmp);
        }

        return out.join('');
    }

    this.repeatString = function (tplDom, arr, func=null) {
        if (tplDom.length === 0) {
            this.error('字符串长度为空');
            return;
        }

        if (arr.length === 0) {
            this.error('数据为空');
            return tplDom;
        }

        let tpl = tplDom;
        let out = '';
        for (let i=0; i<arr.length; i++) {
            if (typeof func === 'function') {
                arr[i] = func(arr[i]);
            }
            let map = arr[i];
            let tmp = tpl;
            for (let j in map) {
                let re = new RegExp('{' + j + '}', 'g');
                tmp = tmp.replace(re, map[j]);
            }

            let re = new RegExp('{_idx}', 'g');
            tmp = tmp.replace(re, parseInt(i)+1);

            out += tmp;
        }

        return out;
    };
}
/**
 *使用举例
    let tb = new zbToolBar();
    let list = [
        {name: '111', id: '111', style:'bg-grey'},
        {name: '222', id: '222', style:'default'},
        {name: '333', id: '333', style:'bg-green'},
    ];
    tb.onClick = function () {
        let id = this.getAttribute('id');
        switch (id) {
            case '111':
                goTop();
                break;
            default:
                break;
        }
    }

    let config = {id: 'tb', position:'bottom'};
    tb.init(list, config);
    tb.replaceNode("aaa"); //将id=aaa的标签替换为 toolbar
 */